
package com.plian.system.service.sys.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.DateUtil;
import com.plian.Tools.StringUtil;
import com.plian.system.common.status.CustomCode;
import com.plian.system.entity.sys.BaseFormColumnName;
import com.plian.system.entity.sys.FormColumnName;
import com.plian.system.entity.sys.SearchColumnName;
import com.plian.system.enumeratea.FieldType;
import com.plian.system.mapper.sys.BaseFormColumnNameMapper;
import com.plian.system.mapper.sys.FormColumnNameMapper;
import com.plian.system.mapper.sys.SearchColumnNameMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.service.sys.system.IBaseFormColumnNameService;
import com.plian.system.service.sys.system.IFormColumnNameService;
import com.plian.system.service.sys.system.ISearchColumnNameService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 表单字段 服务实现类
 *
 * @author jianglei
 * @since 2019-10-23
 */
@Service
@AllArgsConstructor
public class BaseFormColumnNameServiceImpl extends ServiceImpl<BaseFormColumnNameMapper, BaseFormColumnName> implements IBaseFormColumnNameService {
    /**
     * logger属性.
     */
    private static final Logger logger  = LoggerFactory.getLogger(BaseFormColumnNameServiceImpl.class);

    private IFormColumnNameService formColumnNameService;

    private FormColumnNameMapper formColumnNameMapper;

    private ISearchColumnNameService searchColumnNameService;

    private SearchColumnNameMapper searchColumnNameMapper;


    @Override
    public R createByTableName(BaseFormColumnName baseFormColumnName) {
        if (baseFormColumnName.getTableName() == null){
            return new R(CustomCode.builder().message("表名为空").code(1999).success(false).build());
        }

        if (baseFormColumnName.getName() == null){
            return new R(CustomCode.builder().message("表单名为空").code(1999).success(false).build());
        }

        if (baseFormColumnName.getFormType() == null){
            return new R(CustomCode.builder().message("表单类型为空").code(1999).success(false).build());
        }

        BaseFormColumnName old = getOne(new LambdaQueryWrapper<BaseFormColumnName>().eq(BaseFormColumnName::getTableName, baseFormColumnName.getTableName())
                .eq(BaseFormColumnName::getFormType, baseFormColumnName.getFormType()));
        if (old != null){
            return new R(CustomCode.builder().message("该表单已创建").code(1999).success(false).build());
        }

        List<FormColumnName> list = formColumnNameMapper.getColumnName(baseFormColumnName.getTableName());
        if (CollectionUtil.isEmpty(list)){
            return new R(CustomCode.builder().message("该表不存在").code(1999).success(false).build());
        }

        boolean result = save(baseFormColumnName);
        list.stream().forEach(entity -> {
            entity.setFormType(baseFormColumnName.getFormType());
            entity.setColumnName(StringUtil.underlineToHump(entity.getColumnName()));
            entity.setIsShow(2);
            entity.setBaseId(baseFormColumnName.getId());
        });

        if (result){
            formColumnNameService.saveBatch(list);
        }
        return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);

    }

    @Override
    public R updateSearchColumn(Long baseId) {
        BaseFormColumnName baseFormColumnName = getById(baseId);
        if (baseFormColumnName == null){
            return new R(CustomCode.builder().message("该表未生成数据").code(1999).success(false).build());
        }
        List<SearchColumnName> oldList = searchColumnNameService
                .list(new LambdaQueryWrapper<SearchColumnName>().eq(SearchColumnName::getBaseId, baseId));
        List<SearchColumnName> list = searchColumnNameMapper.getColumnName(baseFormColumnName.getTableName());
        if (CollectionUtil.isEmpty(list)){
            return new R(CustomCode.builder().message("该表不存在").code(1999).success(false).build());
        }
        Map<String, SearchColumnName> fieldNameMap = oldList.stream().collect(Collectors.toMap(SearchColumnName::getColumnName, columnName -> columnName));
        List<SearchColumnName> updateList = new ArrayList<>();
        List<SearchColumnName> addList = new ArrayList<>();
        for (SearchColumnName searchColumnName : list){
            String columnName = StringUtil.underlineToHump(searchColumnName.getColumnName());
            if (fieldNameMap.containsKey(columnName)){
                SearchColumnName entity = fieldNameMap.get(columnName);
                entity.setSearchColumnName(searchColumnName.getSearchColumnName());
                entity.setIsSearch(1);
                entity.setIsDict(1);
                columnTypeSet(entity);
                updateList.add(entity);
            }else {
                initColumnName(searchColumnName, baseFormColumnName);
                addList.add(searchColumnName);
            }
        }
        if (CollectionUtil.isNotEmpty(updateList)){
            searchColumnNameService.updateBatchById(updateList);
        }
        if (CollectionUtil.isNotEmpty(addList)){
            searchColumnNameService.saveBatch(addList);
        }

        return new R(CommonCode.SUCCESS);
    }

    private void initColumnName(SearchColumnName entity, BaseFormColumnName baseFormColumnName){
        entity.setFormType(baseFormColumnName.getFormType());
        entity.setColumnName(StringUtil.underlineToHump(entity.getColumnName()));
        entity.setIsShow(2);
        entity.setBaseId(baseFormColumnName.getId());
        entity.setIsSearch(1);
        entity.setIsDict(1);
        columnTypeSet(entity);
    }

    private void columnTypeSet(SearchColumnName entity){
        if (FieldType.DATE.getDataType().equals(entity.getFieldType())){
            entity.setFormatStr(DateUtil.PATTERN_DATE);
        }
        if (FieldType.DATETIME.getDataType().equals(entity.getFieldType())){
            entity.setFormatStr(DateUtil.PATTERN_DATETIME);
        }
        entity.setFieldType(FieldType.dataTypeToFieldType(entity.getFieldType()));
    }

    @Override
    public R edit(BaseFormColumnName baseFormColumnName) {
        List<FormColumnName> childList = baseFormColumnName.getFormColumnNameList();
        if (CollectionUtil.isNotEmpty(childList)){
            formColumnNameService.remove(new LambdaQueryWrapper<FormColumnName>().eq(FormColumnName::getBaseId, baseFormColumnName.getId()));
            childList.forEach(formColumnName -> formColumnName.setBaseId(baseFormColumnName.getId()));
            return formColumnNameService.saveBatch(childList) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
        }
        return new R(CommonCode.SUCCESS);
    }

    @Override
    public BaseFormColumnName detail(Long id) {
        BaseFormColumnName baseFormColumnName = getById(id);
        baseFormColumnName.setFormColumnNameList(formColumnNameService.list(new LambdaQueryWrapper<FormColumnName>().eq(FormColumnName::getBaseId, id)));
        return baseFormColumnName;
}

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BaseFormColumnName baseFormColumnName = getById(id);
            if (baseFormColumnName == null) {
                return false;
            }
        }

        boolean result = removeByIds(ids);
        if (result){
            formColumnNameService.remove(new LambdaQueryWrapper<FormColumnName>().in(FormColumnName::getBaseId, ids));
        }
        return result;
    }

}
